package com.cy.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cy.study.common.BasePageReq;
import com.cy.study.entity.*;
import com.cy.study.exception.BusinessException;
import com.cy.study.mapper.*;
import com.cy.study.req.ExamAddReq;
import com.cy.study.req.ExamDeleteReq;
import com.cy.study.req.ExamPageReq;
import com.cy.study.req.UserExamPageReq;
import com.cy.study.res.*;
import com.cy.study.service.ExamService;
import com.cy.study.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class ExamServiceImpl extends ServiceImpl<ExamMapper, ExamEntity> implements ExamService {

    private final MajorMapper majorMapper;
    private final QuestionMapper questionMapper;
    private final UserExamRecordMapper userExamRecordMapper;
    private final ExamRecordMapper examRecordMapper;

    @Override
    public Integer addExam(ExamAddReq req) {
        //先检查课程编号是不是存在
        Integer courseNum = req.getCourseNum();
        if(courseNum==null){
            throw new BusinessException("请检查参数中课程编号是否存在");
        }
        QueryWrapper<MajorEntity> majorWrapper = new QueryWrapper<>();
        majorWrapper.lambda().like(MajorEntity::getCourseNums,req.getCourseNum());
        Long count = majorMapper.selectCount(majorWrapper);
        if(count==0){
            throw new BusinessException("课程编号不合法，请重试");
        }
        ExamEntity examEntity = new ExamEntity();
        BeanUtils.copyProperties(req,examEntity);
        examEntity.setCreateTime(LocalDateTime.now());
        this.save(examEntity);
        return examEntity.getId();
    }

    @Override
    public Page<ExamPageRes> pageExam(ExamPageReq req) {
        Page page = new Page(req.getPageNum(),req.getPageSize());
        Page<ExamPageRes> res = this.getBaseMapper().pageExam(req,page);
        return res;
    }

    @Override
    public ExamDetailRes examDetail(Integer examId) {
        //试卷信息
        ExamDetailRes res = new ExamDetailRes();
        ExamEntity exam = this.getBaseMapper().selectById(examId);
        res.setExamEntity(exam);
        MajorEntity major = majorMapper.selectById(exam.getMajorId());
        res.setMajorName(major.getMajorName());
        QueryWrapper<QuestionEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(QuestionEntity::getExamId,examId);
        List<QuestionEntity> questions = questionMapper.selectList(wrapper);
        res.setList(questions);
        return res;
    }

    @Override
    public Page<UserCenterPageExamRes> userCenterPageExam(BasePageReq req) {
        Page page = new Page(req.getPageNum(),req.getPageSize());
        Integer userId = SecurityUtils.getUserId();
        Page<UserCenterPageExamRes> res = this.getBaseMapper().userCenterPageExam(userId,page);
        return res;
    }

    @Override
    public CenterExamRes userCenterExamDetail(Integer examRecordId) {
        Integer userId = SecurityUtils.getUserId();
        CenterExamRes res = new CenterExamRes();
        UserExamRecordEntity record = userExamRecordMapper.selectById(examRecordId);
        ExamEntity exam = this.getById(record.getExamId());
        res.setId(record.getId());
        res.setExamName(exam.getExamName());
        res.setIntroduce(exam.getIntroduce());
        res.setFinishTime(record.getFinishTime());
        //找出试卷记录
        List<CenterQuestionRecordRes> list = examRecordMapper.getUserRecord(userId,examRecordId);
        res.setList(list);
        return res;
    }

    @Override
    public Page<UserExamPageRes> userExamPage(UserExamPageReq req) {
        Page page = new Page(req.getPageNum(),req.getPageSize());
        Page<UserExamPageRes> res = this.getBaseMapper().userExamPage(req,page);
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteExam(ExamDeleteReq req) {
        //先看有没有用户做过，有做过的不能删
        QueryWrapper<UserExamRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UserExamRecordEntity::getExamId,req.getExamId());
        Long aLong = userExamRecordMapper.selectCount(wrapper);
        if(aLong>0){
            throw new BusinessException("已有用户练习过试卷，无法删除");
        }
        else {
            //先删除题目
            QueryWrapper<QuestionEntity> questionEntityQueryWrapper = new QueryWrapper<>();
            questionEntityQueryWrapper.lambda().eq(QuestionEntity::getExamId,req.getExamId());
            questionMapper.delete(questionEntityQueryWrapper);
            //再删除试卷
            this.removeById(req.getExamId());
        }
    }

}
